package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.myException.MergeException;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDone;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Resource
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     *  //获取所有未领取的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        //需要限制采购单状态，0或1都是刚新建而未被领取的
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    //将采购单进行合并
    //http://localhost:88/api/ware/purchase/merge
    //items: [1, 2]    采购需求id
    //purchaseId: 1   采购单id
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {

        /*
        我们有两种方式合并采购需求：
        1.选中采购需求以及要合并到的采购单
        2.选中采购需求但不选择要合并的采购单，这时系统会现为我们创建一个采购单，并进行合并

        基于以上情况，我们需要先对purchaseId进行判断
         */
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确认采购单状态是0或者1才能够合并   注意，我们将允许重复分配
        Long finalPurchaseId = purchaseId;
        PurchaseEntity byId = this.getById(purchaseId);
        if(byId.getStatus() != WareConstant.PurchaseStatusEnum.CREATED.getCode() &&
                byId.getStatus() != WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
            throw new MergeException("不可选中次采购单,该采购单已经被领取，请换一个");
        }

        List<Long> items = mergeVo.getItems();

        List<PurchaseDetailEntity> collect = items.stream().map((i) -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);
        PurchaseEntity entity = new PurchaseEntity();
        entity.setUpdateTime(new Date());
        entity.setId(purchaseId);
        baseMapper.updateById(entity);
    }

    /**
     *
     * @param ids : 采购单id
     */
    @Override
    public void received(List<Long> ids) {
        //0.确认当前采购单是新建或已分配状态，这样才能够领取
        List<PurchaseEntity> collect = ids.stream().map((id) -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            return (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()) ||
                    (item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        }).map((item) -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RESEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //1.如果领的是2号采购单，就需要改变2号采购单的状态  状态是已领取
        this.updateBatchById(collect);
        //2.有关2号采购单的所有采购需求也都应该进行修改      状态是正在采购
        collect.forEach((item) -> {
            //先拿出当前这个采购单所有的采购项
            List<PurchaseDetailEntity> list = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect1 = list.stream().map((i) -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                purchaseDetailEntity.setId(i.getId());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect1);
        });
    }

    /**
     *         private Long id; //采购单id
     *         private List<PurchaseItemDoneVo> items;  //采购需求
     * @param purchaseDone
     */
    @Override
    @Transactional
    public void done(PurchaseDone purchaseDone) {

        //1.改变采购项状态
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = purchaseDone.getItems();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            }else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());

                //2.将成功的采购进行入库  wms_ware_sku  当前商品给  哪个 仓库入  几个
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updates);


        //3.改变采购单状态
        Long id = purchaseDone.getId();

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag? WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);




    }

}